<!-- 上传发票与回单 -->
<template>
<section :class="{'common-text-block-section': isSinglePart}">
    <section class="title-section" :class="{'inner-title-section': !isSinglePart}">
        <div class="title">
            上传发票与回单
        </div>
    </section>
    <section class="upload-file-section">
        <div class="form-item">
            <section class="title-section">
                上传发票
            </section>
            <el-upload
                ref="invoice"
                drag
                accept=".jpg,.png"
                action="RECEIPT"
                :before-remove="handleRemove"
                :data="{key: 'invoice'}"
                :http-request="uploadFile"
                multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">
                    <div>提示:</div>
                    <div>1. 票据包含增值税发票、机打发票和餐票</div>
                    <div>2. 务必保证票据文字清晰可见，若有明显折痕请手动输入，否则影响出账结果</div>
                </div>
            </el-upload>
        </div>
        <div class="form-item">
            <section class="title-section">
                上传银行回单
            </section>
            <div class="el-upload-dragger" id="header-radio">
                    <div class="radio-description">
                    <el-row :gutter="1">
                        <el-col :span="10">请选择上传凭证类型:</el-col>
                       <el-col :span="12">
                    <el-radio v-model="banktype" label="0">暂不上传</el-radio>
                    <el-radio v-model="banktype" label="1">银行流水</el-radio>
                    <el-radio v-model="banktype" label="2">银行回单</el-radio>
                    </el-col>
                    </el-row>
                    </div>
                    <div class="el-upload__tip">提示： 建议选择银行流水作为凭证，选择银行回单可能会导致部分信息不准确</div>
            </div>
            <el-upload
            v-if="banktype == 2"
                ref="bankSlip"
                drag
                accept=".jpg,.png"
                action="BILL"
                 :before-remove="handleRemove"
                :data="{key: 'bankSlip'}"
                :http-request="uploadFile"
                multiple
                id="bankupload">
                <i class="el-icon-upload" id="bankicon"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">
                    <div>提示:</div>
                    <div>1. 务必保证票据文字清晰可见，若有明显折痕请手动输入，否则影响出账结果</div>
                </div>
            </el-upload>
            <!-- <div class="el-upload-dragger" id="header-radio"> -->
        <div v-if="uploadInfo">
        <div v-if="banktype==1" class="single-line">
                <label class="iconfont icon-bank">银行流水:</label>
                <span class="bank" :class="{uploaded: uploadInfo.bank}">
                    {{uploadInfo.bank ? '已上传' : '未上传' }}
                </span>
            <bankStatementUpload @uploadBankFinished="getUploadFinished" ref="bankStatementUploadInSpecial"  :accountBillData="accountBillData"/>
            </div>
        </div>
        </div>
        <div class="form-item">
            <section class="title-section">
                上传特殊票据
            </section>
            <el-upload
                ref="specInvoice"
                drag
                accept=".jpg,.png"
                action="MIX_RECEIPT"
                 :before-remove="handleRemove"
                :data="{key: 'specInvoice'}"
                :http-request="uploadFile"
                multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">
                    <div>提示:</div>
                    <div>火车票/飞机票行程单/汽车票/过路费发票可在此上传，其他票据请手动添加分录</div>
                </div>
            </el-upload>
        </div>
    </section>
</section>
</template>
<script>
/**
 * @file 上传资料页 / 上传发票部分
 */

import 'element-ui/lib/theme-chalk/upload.css';
import bankStatementUpload from '@/components/bankStatementUpload';
import {getFileType} from "@/components/map";

export default {
    props: {
        isSinglePart: {
            type: Boolean,
            default: true
        },
        uploadInfo: {
            type: Object,
            default: null
        },
        accountBillData: {
            type: Object,
            default: null
        },

    },
    components: {
        bankStatementUpload
    },
    data() {
        return {
            invoiceFileIds: [],
            bankSlipFileIds: [],
            specInvoiceFileIds: [],
            uidFileidMap: {},
            banktype:1,
            uploadBankFinished: false,
            successFlagNum: [] // 标记是否全部发票都传送且处理完毕
        };
    },
    methods: {

        /**
         * 上传文件，当一次性选择多个文件时，会分多次上传
         *
         * @param {Object} fileData 文件数据
         */
        uploadFile(fileData) {
            const formData = new FormData();
            console.log("fileData:", fileData);
            formData.append('file', fileData.file);
            formData.append('cName', this.accountBillData.companyName);
            formData.append('fileType', getFileType(fileData.action));
            formData.append('fileName', fileData.file.name);
            // 将此发票放入待处理队列中
            this.successFlagNum.push(fileData.file.name)

            return this.$http.post(
                "/upload/file",
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    onUploadProgress: progressEvent => {
                        const complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                        fileData.onProgress({ percent: complete })
                    }
                }
            ).then(res => {
                if (res.code == 0) {
                    this[`${fileData.data.key}FileIds`].push(res.data.fileId);
                    //
                    this.uidFileidMap[fileData.file.uid] = {fileId:res.data.fileId, key:fileData.data.key, type:getFileType(fileData.action)}
                    //type: 0表示发票， 1表示回单
                }
                else {
                    this.$message.error(`${fileData.file.name}上传失败`);
                    // 从列表中删除上传失败的文件
                    const uploadFiles = this.$refs[fileData.data.key].uploadFiles;
                    const index = uploadFiles.findIndex(item => item.uid === fileData.uid);
                    uploadFiles.splice(index, 1);
                }
                // 剔除后端已经处理好的票据
                this.successFlagNum.pop()
                // 判断此时是否可以打开保存按钮
                this.uploadBankFinished = this.successFlagNum.length == 0? true: false;
                this.$emit("uploadBankFinished", this.uploadBankFinished);
            });
        },
        handleRemove(file, fileList){
            const deleteApi = "/upload/deleteReceiptBill";
            const {fileId: fileId, key: key, type: type} = this.uidFileidMap[file.uid]
            const params ={fileId:fileId,
                    cName: this.accountBillData.companyName,
                    type: type
            };
            // uploadFiles.splice(index, 1);
            this.$http.get(deleteApi, {params: params}).then(res => {
                if (res.code == 0) {
                    const index = this[`${key}FileIds`].findIndex(item => item == fileId);
                    this[`${key}FileIds`].splice(index, 1)
                    return true;
                }
                else {
                    this.$message.error(`${file.name}删除失败`);
                    return false;
                    // 从列表中删除上传失败的文件
                }
            })
        },
        getValue() {
          let bankStatementFileIds = [];
        //   if (!this.uploadFinished){
        //         var start = new Date();
        //         while(new Date() - start < 3000) { // delay 2 sec
        //             ;
        //         }
        //         this.uploadFinished = false;
        //     }

            if (this.$refs.bankStatementUploadInSpecial) {
                bankStatementFileIds = this.$refs.bankStatementUploadInSpecial.getValue();
            }

            return {
                invoiceFileIds: this.invoiceFileIds,
                bankSlipFileIds: this.bankSlipFileIds,
                specInvoiceFileIds: this.specInvoiceFileIds,
                bankStatementFileIds
            };
        },
        getUploadFinished(uploadFinished) {
            this.uploadBankFinished = uploadFinished;
            console.log("uploadBankFinished", this.uploadBankFinished)
            this.$emit("uploadBankFinished", this.uploadBankFinished);
            this.uploadBankFinished = false;
        }
    },
    watch:{
        banktype(newValue, oldValue){
            if (newValue == 1){
                this.uploadBankFinished = false;
                this.$emit("uploadBankFinished", this.uploadBankFinished);
            }else {
                this.uploadBankFinished = true;
                this.$emit("uploadBankFinished", this.uploadBankFinished);
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import '../../../assets/var.less';
.upload-file-section {
    display: flex;
    padding: 0 0 20px 0;
    // .form-item {
    //     flex: 1;
    // }
    .form-item ~ .form-item {
        margin-left: 20px;
    }
    .title-section {
        margin: 0 0 10px 0;
        padding-bottom: 10px;
        line-height: 1.5em;
    }
    .upload-item {
        display: inline-block;
    }
}
#bankicon{
    margin-top:0;
}

// /deep/ 可以不必是父子组件关系
#bankupload /deep/ .el-upload-dragger{
        height: 100px;
        width:650px;
}

.form-item #header-radio{
    width: 650px;
        height: 80px;
        padding-bottom: 20px;
}
.radio-description{
    margin-top: 10px;
    margin-bottom: 6px;
}
.single-line {
    padding: 5px 0;
    display: flex;
    > label {
        flex: 0 0 100px;
        &::before {
            margin-right: 5px;
        }
    }
    > span {
        flex: 0 0 60px;
        font-size: 14px;
        line-height: 26px;
        &.bank {
            // color: @color-error;
        }
        &.uploaded {
            color: @color-green;
        }
    }
}
</style>
